<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属课程" prop="trainingId">
        <el-select  v-model="queryParams.trainingId" clearable filterable placeholder="请选择" @change="getCourse">
          <el-option
            v-for="item in courseList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试卷类型" prop="paperType">
        <el-select v-model="queryParams.paperType" placeholder="请选择试卷类型" clearable>
          <el-option
            v-for="dict in dict.type.exam_paper_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试卷名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入试卷名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试卷状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择试卷状态" clearable>
          <el-option
            v-for="dict in dict.type.exam_paper_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['answer:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['answer:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['answer:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['answer:paper:export']"
        >下载模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="自动编号" align="center" prop="id" v-if="true"/>
      <el-table-column label="所属课程" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="试卷类型" align="center" prop="paperType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exam_paper_type" :value="scope.row.paperType"/>
        </template>
      </el-table-column>
      <el-table-column label="试卷名称" align="center" :show-overflow-tooltip="true"  >
        <template slot-scope="scope">
          <router-link :to="'/answer/composition/index/'+ scope.row.id " class="link-type" >
            <span>{{ scope.row.paperName }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="阅卷人账户" align="center" prop="name" />
      <el-table-column label="试卷分数" align="center" prop="totalScore" />
      <el-table-column label="及格分数" align="center" prop="passingScore" />
      <el-table-column label="考试时间" align="center" prop="startTime" :show-overflow-tooltip="true" />
      <el-table-column label="考试时长" align="center" prop="examDuration" >
        <template slot-scope="scope">
          {{ scope.row.examDuration }}分钟
        </template>
      </el-table-column>
      <el-table-column label="试卷状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exam_paper_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['answer:paper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['answer:paper:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属课程" >
          <el-select v-model="form.title" filterable placeholder="请选择" @change="getCourse">
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷类型" prop="paperType">
          <el-select v-model="form.paperType" placeholder="请选择试卷类型">
            <el-option
              v-for="dict in dict.type.exam_paper_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷名称" prop="paperName">
          <el-input v-model="form.paperName" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="阅卷人账户" prop="markingAccount">
<!--          <el-input v-model="form.markingAccount" placeholder="请输入阅卷人账户" />-->
          <el-select v-model="form.name" filterable placeholder="请选择" @change="getTeacher">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试卷分数" prop="totalScore">
          <el-input v-model="form.totalScore" placeholder="请输入试卷分数" />
        </el-form-item>
        <el-form-item label="及格分数" prop="passingScore">
          <el-input v-model="form.passingScore" placeholder="请输入及格分数" />
        </el-form-item>
        <el-form-item label="考试时间" prop="startTime">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="-"
            v-model="form.startTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试时长" prop="examDuration">
          <el-input v-model="form.examDuration" placeholder="请输入考试时间" />
        </el-form-item>
        <el-form-item label="试卷状态">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.exam_paper_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPaper, listCompositionByPaperId,getPaper, delPaper, addPaper, updatePaper } from "@/api/answer/paper";
import { listTeacher } from "@/api/edu/teacher"
import { queryAll } from "@/api/edu/course";
import { getToken } from "@/utils/auth";
export default {
  name: "Paper",
  dicts: ['exam_paper_status', 'exam_paper_type'],
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入试卷",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/answer/paper/addPaperByExcel"
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      courseName:"",
      // 试卷管理表格数据
      paperList: [],
      courseList:[],
      teacherList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        trainingId: undefined,
        paperId:undefined,
        paperType: undefined,
        paperName: undefined,
        state: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "自动编号不能为空", trigger: "blur" }
        ],
        trainingId: [
          { required: true, message: "所属课程id不能为空", trigger: "blur" }
        ],
        paperType: [
          { required: true, message: "试卷类型不能为空", trigger: "change" }
        ],
        paperName: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" }
        ],
        markingAccount: [
          { required: true, message: "阅卷人账户不能为空", trigger: "blur" }
        ],
        totalScore: [
          { required: true, message: "试卷分数不能为空", trigger: "blur" }
        ],
        passingScore: [
          { required: true, message: "及格分数不能为空", trigger: "blur" }
        ],
        examDuration: [
          { required: true, message: "考试时间不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "试卷状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {

    this.getList();
    this.queryAll();

  },
  methods: {
    getCourse(value){
      console.log(value)
      this.form.trainingId=value
    },
    getTeacher(value){
      this.form.markingAccount=value
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /**
     * 查询所有课程
     */
    queryAll(){
      queryAll().then(res=>{
        this.courseList=res.data
        console.log(res)
      })
    },
    /** 查询试卷管理列表 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then(response => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listTeacher().then(response => {
        this.teacherList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        trainingId: undefined,
        paperType: undefined,
        paperName: undefined,
        markingAccount: undefined,
        totalScore: undefined,
        passingScore: undefined,
        examDuration: undefined,
        state: 0,
        version: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试卷管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getPaper(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改试卷管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updatePaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除试卷管理编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delPaper(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('answer/paper/export', {
        ...this.queryParams
      }, `paper_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
